
import { _decorator, Component, Prefab, CCInteger, Vec3, instantiate, AudioClip, AudioSource, Node } from 'cc';
import { eventTarget } from './Globle';
const { ccclass, property } = _decorator;

@ccclass('GameControl')
export class GameControl extends Component {
    @property(Node) wrap: Node;
    @property(Prefab) player: Prefab;
    @property(AudioClip) level1_loop: AudioClip;
    @property(CCInteger) player_life: number;
    private audioSource: AudioSource;
    private isSetAudio: boolean = false;
    onLoad() {
        this.audioSource = this.getComponent(AudioSource);
    }
    start() {
        eventTarget.on("playerDied", this.onPlayerDied, this);
        this.audioSource.node.on(AudioSource.EventType.ENDED, this.onAudioEnd, this);
    }

    private onAudioEnd() {
        if (this.isSetAudio) return;
        this.audioSource.stop();
        this.audioSource.clip = this.level1_loop;
        this.audioSource.loop = true;
        this.audioSource.play();
        this.isSetAudio = true;
    }

    //玩家死亡
    private onPlayerDied(playerPos: Vec3) {
        if (this.player_life > 0) {
            this.scheduleOnce(() => {
                let player = instantiate(this.player);
                player.position = playerPos;
                this.node.addChild(player);
                this.player_life--;
            }, 1)
        } else {
            this.wrap.active = true;
        }
    }
}
